package controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.Category;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class CategoryServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setCharacterEncoding("utf-8");
		resp.setHeader( "Cache-Control", "public, max-age=86400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		String path = ((HttpServletRequest)req).getRequestURI();
		
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	try {
				req.getRequestDispatcher("/404error.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
        	return ;
        }

		// skip one token /sites/gooogle.com (remove sites)
		st.nextToken();
		String name = st.nextToken();
		name=URLDecoder.decode(name,"UTF-8");
		if(name!=null&&name.length()>0)
		{
			try {
    			ObjectifyService.register(Category.class);
    		} catch (Exception e) {
    			// TODO: handle exception
    		}
    		Objectify objectify = ObjectifyService.begin();
			
			try {
				Category cate1 = objectify.get(new Key<Category>(Category.class, name));
				req.setAttribute("cate", cate1);
			} catch (Exception e) {
				
			}
		}
		req.setAttribute("name", name);
		try {
			req.getRequestDispatcher("/category.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
